import {
  apiSelectSource,
  apiSelectCity,
  apiSelectCate,
  apiSelectPruduct
} from '@/api/clue'

const state = () => {
  return {
    cityList: [], // 地区列表
    cateList: [], // 行业分类列表
    clueSource: [], // 线索来源
    vipList: [] // 会员产品列表
  }
}

const mutations = {
  SET_CITY_LIST: (state, list) => {
    state.cityList = list
  },
  SET_CATE_LIST: (state, list) => {
    state.cateList = list
  },
  SET_CLUE_SOURCE: (state, list) => {
    state.clueSource = list
  },
  SET_VIP_LIST: (state, list) => {
    state.vipList = list
  }
}

const actions = {
  getCityList({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.cityList.length > 0) {
        resolve(state.cityList)
      } else {
        apiSelectCity()
          .then((res) => {
            commit('SET_CITY_LIST', res.data)
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },

  getCateList({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.cateList.length > 0) {
        resolve(state.cateList)
      } else {
        apiSelectCate()
          .then((res) => {
            res.data.forEach((item) => {
              if (item.children.length === 0) {
                delete item.children
              } else {
                item.children.forEach((item2) => {
                  if (item2.children.length === 0) {
                    delete item2.children
                  }
                })
              }
            })
            commit('SET_CATE_LIST', res.data)
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },
  getClueSource({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.clueSource.length > 0) {
        resolve(state.clueSource)
      } else {
        apiSelectSource()
          .then((res) => {
            commit('SET_CLUE_SOURCE', res.data)
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },
  getVipList({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.vipList.length > 0) {
        resolve(state.vipList)
      } else {
        apiSelectPruduct()
          .then((res) => {
            commit('SET_VIP_LIST', res.data)
            resolve(res.data)
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
